var mail = @options("mail") || {};
const nodemailer = require('nodemailer');
var mailTransporters = {};

@lab(function(lab) {

    return @.async(async function() {

        await @promise("slime.subscribe.ready");

    }).all(@.keys(mail), function(ou) {

        lab.slime.core.@initSession({}, ou).then(function(currentOU) {

            lab.slime_subscribe.mail.@saveSettings(currentOU, mail[ou]).then(async function(result) {

                mailTransporters[currentOU.id] = nodemailer.createTransport({
                    host: result.smtp_host,
                    port: result.smtp_port,
                    secureConnection: result.use_ssl,
                    auth: {
                        user: result.smtp_username,
                        pass: result.smtp_password
                    },
                    tls: {
                        rejectUnauthorized: false
                    }
                }, {
                    from: result.smtp_username
                });

            }).pipe(this);

        }).then(async function () {

            @mew.emit(`slime.subscribe.mailer.${ou}.ready`);

        }).pipe(this);
    });
}).rejected(function(error) {
    @error(error);
})

module.exports = function(lab) {
    return {
        @sendMail : function ({ouid, address, title, html, content, files = []}) {
            return @.async(function() {
                mailTransporters[ouid].sendMail({
                    to: address,
                    subject: title,
                    html: html,
                    text: content,
                    attachments: files.filter(function(file){
                        return file.path || file.content;
                    }).map((file, index) => {
                        let result = {}
                        if (file.filename) {
                            result.filename = file.filename
                        } else {
                            result.filename = `附件${index + 1}`
                        }
                        if (file.path) {
                            result.path = file.path
                        } else {
                            result.content = file.content || ""
                        }
                        return result
                    })
                }, this.test);
            });
        },
        @saveSettings: function(currentOU, { host, username, port, password, sender, ssl = true }) {

            if (!currentOU) {
                throw @lab.errors.invalid_parameters;
            }

            if (!host || !username || !password) {
                throw @lab.errors.invalid_parameters;
            }

            if (!sender) {
                sender = username;
            }

            return lab.find("slime_mail_providers", {
                ouid: currentOU.id,
                smtp_host: host
            }).then(function(provider) {

                var form = {
                    smtp_host: host,
                    smtp_username: username,
                    smtp_password: password,
                    smtp_sender: sender,
                    smtp_port: port || 25,
                    use_ssl: ssl ? true : false,
                    last_update: Date.now()
                };

                if (provider) {
                    return lab.update("slime_mail_providers", provider, form);
                } else {
                    return lab.create("slime_mail_providers", @.merge.simple(form, {
                        create_date: Date.now(),
                        ouid: currentOU.id
                    }));
                }

            })
        }
    }
}